import React, { Component } from 'react'
import classnames from 'classnames'

export class TodoItem extends Component {
    state = {
        cgId:'',
        cgContent:''
    }
    inputRef = React.createRef()
    render() {
        const {item} = this.props
        return (
            <li className={classnames({completed:item.finish,editing:item.id===this.state.cgId})}>
                <div className="view">
                    <input className="toggle" type="checkbox" checked={item.finish} onChange={() => this.cgFinish(item.id)}/>
                    <label onDoubleClick={() => this.cgItemInfo(item)}>{item.content}</label>
                    <button className="destroy" onClick={() => this.delitem(item.id)}></button>
                </div>
                <input className="edit" 
                    value={this.state.cgContent} 
                    onChange={this.cgItem} 
                    onKeyUp={this.cancelCg} 
                    onBlur={()=>{this.setState({cgId:'',cgContent:''})}}
                    ref={this.inputRef}
                />
            </li>
        )
    }

    cgFinish = (id) => {
        this.props.cgFinishById(id)
    }

    delitem = (id) => {
        this.props.delitemById(id)
    }

    cgItemInfo = ({id,content}) => {
        // 这里用到 setState 的第二个参数 回调函数 该函数会在 dom 更新后立即执行
        // 不放在 componentDidUpdate 里是因为但凡别的地方修改 cgId 都会调用 this.inputRef.current.focus()
        this.setState({
            cgId:id,
            cgContent:content
        },()=>{this.inputRef.current.focus()})
    }

    cgItem = (e) => {
        this.setState({
            cgContent:e.target.value
        })
    }

    cancelCg = (e) => {
        if(e.keyCode === 27) {
            this.setState({
                cgId:'',
                cgContent:''
            })
        }
        if(e.keyCode === 13) {
            this.props.cgItemById(this.state.cgId,this.state.cgContent)
            this.setState({
                cgId:'',
                cgContent:''
            })
        }
    }

    // componentDidUpdate() {
    //     this.inputRef.current.focus()
    // }
}

export default TodoItem